package yxy.cherry.router.server;

import yxy.apple.logger.Logger;
import yxy.apple.logger.Logger.Level;
import yxy.apple.protobuf.Message.Parcal;
import yxy.banana.server.internal.InternalServerHandler;
import yxy.banana.socket.NetworkElement;
import yxy.banana.socket.ParcalUtility;
import yxy.cherry.router.Configuration;
import yxy.cherry.router.Reactor;

public class RouterServerHandler extends InternalServerHandler {
	private static final Logger logger = Logger.create(RouterServerHandler.class);
	private String key = null;

	public String key() {
		return key;
	}

	void setKey(String key) {
		this.key = key;
	}

	@Override
	protected boolean business(Parcal parcal) throws Exception {
		return this.transmit(parcal);
	}

	/**
	 * 路由转发
	 * @return
	 * @throws Exception
	 */
	boolean transmit(Parcal parcal) throws Exception {
		// NetworkElement sne = NetworkElement.assemble(source);
		NetworkElement dne = NetworkElement.assemble(parcal.getDestination());
		if (dne.system() == this.system()) {
			RouterServerHandler handler = Reactor.instance.clustered().balance(dne.cluster());
			if (handler != null) {
				handler.send(parcal);
				if (Logger.enabled(Level.Debug)) {
					String description = ParcalUtility.toString(parcal);
					logger.info("转发消息...\r\n%s\r\n%s\r\n%s", this.toString(), handler.toString(), description);
				}
				return true;
			} else {
				logger.error("向%s转发消息时找不到可用通道，请检查内部连接！\r\n", dne, this.toString());
				return false;
			}
		} else {
			String description = ParcalUtility.toString(parcal);
			logger.error("要求转发的消息需要暂未实现的system路由策略，请检查发送端代码！\r\n%s\r\n%s", this.toString(), description);
			return false;
		}
	}

	@Override
	public int system() {
		return Configuration.shared().SystemID;
	}

	@Override
	public int cluster() {
		// 路由中心的cluster无意义，全部填0
		return 0;
	}

}
